package com.alibaba.cloud.authorization.config;

import com.alibaba.cloud.authorization.token.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @descript 保护授权端点
 * @author focus
 * @date 2025/8/13
 */
@Configuration
@EnableWebSecurity
public class AuthorizationSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailService userDetailService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(
                        "/oauth/authorize"
                        ,"/thirdLogin"
                        ,"/oauth/token"
                ).permitAll()
                .antMatchers("/js/**")
                .permitAll() //放行静态资源
                .anyRequest().authenticated() // 其他任意请求，需要认证
                .and()
                .formLogin()
                .loginPage("/thirdLogin")
                .loginProcessingUrl("/login")
//                .defaultSuccessUrl("/oauth/authorize")
                .permitAll()
                .and()
                .csrf()
                .disable();
//                .exceptionHandling().authenticationEntryPoint(new AuthException());
//        http.addFilterBefore(new AuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(getPasswordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
